import mongoose from 'mongoose';
import { DicModel } from '../schemas/system/Dic';
import { RoleModel } from '../schemas/system/Role';
import { UserModel } from '../schemas/system/User';
import { TenantModel } from '../schemas/system/Tenant';
export const initializeSystemAdmin = async () => {
    const session = await mongoose.startSession();
    session.startTransaction();

    try {
        // 使用辅助函数简化重复逻辑
        const systemRoleDict = await findOrCreateSchema(
            DicModel,
            { type: 'role_type', value: 'system' },
            { type: 'role_type', value: 'system', label: '系统内置', sort: 1, isActive: true, isDefault: true },
            session
        );

        await findOrCreateSchema(
            DicModel,
            { type: 'role_type', value: 'custom' },
            { type: 'role_type', value: 'custom', label: '自定义', sort: 2, isActive: true, isDefault: false },
            session
        );
        const defaultTenant = await findOrCreateSchema(
            TenantModel,
            { name: '默认租户', code: 'default' },
            { name: '默认租户', code: 'default' },
            session
        );
        // 查找或创建管理员角色
        const adminRole = await findOrCreateSchema(
            RoleModel,
            { code: 'admin', name: '管理员' },
            {
                name: '管理员',
                code: 'admin',
                description: '系统管理员角色',
                type: systemRoleDict._id,
                sort: 1,
                isActive: true
            },
            session
        );

        // 查找或创建管理员用户
        await findOrCreateSchema(
            UserModel,
            { roles: { $in: [adminRole._id] }, name: 'Admin' },
            {
                roles: [adminRole._id],
                tenantId: defaultTenant._id,
                name: '超级管理员',
                email: 'admin@example.com',
                password: '123456',
                isActive: true
            },
            session
        );

        // 提交事务
        await session.commitTransaction();
        console.log('✅ 系统管理员初始化成功');
    } catch (error) {
        // 出错时回滚事务
        await session.abortTransaction();
        console.error('❌ 初始化管理员失败，已回滚:', error instanceof Error ? error.message : String(error));
        throw error;
    } finally {
        session.endSession();
    }
}


const findOrCreateSchema = async (
    Model: mongoose.Model<any>,
    filter: Record<string, any>,
    createData: Record<string, any>,
    session: mongoose.ClientSession
): Promise<any> => {
    let schema = await Model.findOne(filter, null, { session }) as any;
    if (!schema) {
        // 修复类型错误：先存储创建的数组，然后获取第一个元素
        const createdDocs = await Model.create([createData], { session });
        schema = createdDocs[0];
    }
    return schema;
}


